
#if UNITY_EDITOR
using OfficeOpenXml;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using Object = UnityEngine.Object;
namespace HHHFramework
{
    public class ExcelDataWindowsEditor : EditorWindow
    {

        [MenuItem("Framework/Excel工具/生成修改ExcelData", false, 1)]
        static void ShowWindow()
        {
            // 获取现有打开的窗口；如果没有，则新建一个窗口：
            var window = GetWindow<ExcelDataWindowsEditor>();
            window.titleContent = new GUIContent("生成修改ExcelData");
            window.Show();
        }
        // SerializeField 用于确保将视图状态写入窗口
        // 布局文件。这意味着只要窗口未关闭，即使重新启动 Unity，也会保持
        // 状态。如果省略该属性，仍然会序列化/反序列化状态。
        [SerializeField] TreeViewState m_TreeViewState;

        //TreeView 不可序列化，因此应该通过树数据对其进行重建。
        BodyModelInfoTreeView bodyModelInfoTreeView;

        MultiColumnHeaderState _multiColHeaderState;
        Rect bodyModelTreeViewRect;
        void OnEnable()
        {
            //检查是否已存在序列化视图状态（在程序集重新加载后
            // 仍然存在的状态）
            if (m_TreeViewState == null)
                m_TreeViewState = new TreeViewState();
        }
        string excelPath;
        Rect excelPathRect;
        private Transform bodyParent;

        private string toggleLabel = "Excel";
        private bool isToggle;
        private static bool isMeridian = false;
        public static bool IsMeridian { get => isMeridian; set => isMeridian = value; }
        public static Dictionary<string, string[]> partsDic = new Dictionary<string, string[]>();

        /// <summary>
        /// 加载数据 按钮按下   生成表格
        /// </summary>
        public void LoadButtonDownClick()
        {
            partsDic = new Dictionary<string, string[]>();

            _multiColHeaderState = CreateStateWith3Cols();
            var multiColHeader = new MultiColumnHeader(_multiColHeaderState);
            multiColHeader.ResizeToFit();
            bodyModelTreeViewRect = new Rect(0, 80, 1000, 700);
            bodyModelInfoTreeView = new BodyModelInfoTreeView(bodyParent, m_TreeViewState, multiColHeader, bodyModelTreeViewRect);
            bodyModelInfoTreeView.Load(excelPath);
        }
        private void OnDisable()
        {
            if (bodyModelInfoTreeView != null) { bodyModelInfoTreeView.Release(); }
        }

        void OnGUI()
        {
            GetExcelUnityAssetPath();
            DragDropExcelPath();
            if (bodyModelInfoTreeView == null) { return; }
            if (bodyModelInfoTreeView.Ini)
            {
                GUILayout.Space(20);
                SetItemValue();
                bodyModelInfoTreeView.OnGUI(bodyModelTreeViewRect);
            }

        }

        /// <summary>
        /// UI  excel路径  加载按钮  等
        /// </summary>
        private void GetExcelUnityAssetPath()
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Excel路径");

            if (GUILayout.Button("Test", GUILayout.Width(50)))
            {
                //地址获取
                //GameObject root = GameObject.Find("BodyParent");
                //Transform modelTrans = GameObject.Find("BodyParent/bodyx/BodyMoveAndScale/男性人体系统/骨骼/guge_jizhui/c02_c03_zhui_jian_pan").transform;
                //Debug.Log( ExcelUtil.GetPath(root.transform, modelTrans));
            }

            EditorGUILayout.EndHorizontal();


            EditorGUILayout.BeginHorizontal();
            //获得一个长300的框  
            excelPathRect = EditorGUILayout.GetControlRect(GUILayout.Width(300));
            //将上面的框作为文本输入框  
            excelPath = EditorGUI.TextField(excelPathRect, excelPath);
            GUILayout.Space(10);
            if (GUILayout.Button("加载", GUILayout.Width(50)))
            {
                if (bodyParent != null)
                {
                    LoadButtonDownClick();
                    Debug.Log($"加载excel文件 {excelPath}");
                }
            }
            GUILayout.Space(10);
            if (GUILayout.Button("Clear", GUILayout.Width(50)))
            {

            }
            GUILayout.Space(10);
            if (GUILayout.Button("保存", GUILayout.Width(50)))
            {
                bodyModelInfoTreeView.SaveExcel(excelPath);
            }
            GUILayout.Space(30);
            EditorGUILayout.LabelField("bodyParent", GUILayout.Width(80));

            bodyParent = (Transform)EditorGUILayout.ObjectField(bodyParent, typeof(Transform), true, GUILayout.Width(100));
            GUILayout.Space(10);

            //EditorGUILayout.LabelField("MenuThreeLayerData", GUILayout.Width(150));

            //menuThreeLayerData = (MenuThreeLayerData)EditorGUILayout.ObjectField(menuThreeLayerData, typeof(MenuThreeLayerData), true, GUILayout.Width(100));
            EditorGUILayout.EndHorizontal();



        }



        private void SetItemValue()
        {
            if (bodyModelInfoTreeView.nowBodyModelItem == null) { return; }
            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.LabelField(bodyModelInfoTreeView.nowBodyModelItem.id.ToString(), GUILayout.Width(40));
            EditorGUILayout.LabelField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.modelName, GUILayout.Width(70));

            EditorGUILayout.LabelField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.path, GUILayout.Width(400));

            EditorGUILayout.LabelField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.infoWord, GUILayout.Width(400));
            #region  修改参数的版本
            //bodyModelInfoTreeView.nowBodyModelItem.bodyModel.chineseName = EditorGUILayout.TextField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.chineseName, GUILayout.Width(50));
            //bodyModelInfoTreeView.nowBodyModelItem.bodyModel.englishName = EditorGUILayout.TextField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.englishName, GUILayout.Width(100));
            //bodyModelInfoTreeView.nowBodyModelItem.bodyModel.infoWord = EditorGUILayout.TextField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.infoWord, GUILayout.Width(50));
            //bodyModelInfoTreeView.nowBodyModelItem.bodyModel.part = EditorGUILayout.TextField(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.part, GUILayout.Width(50));

            //if (GUILayout.Button(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.anatomy, GUILayout.Width(200))) //当点击按钮时，显示下拉菜单
            //{
            //    GenericMenu menu = new GenericMenu(); //初始化GenericMenu 
            //    for (int i = 0; i < localAnatomy.Length; i++)
            //    {
            //        var localAnatomyName = localAnatomy[i];
            //        menu.AddItem(new GUIContent(localAnatomyName), false, () => { bodyModelInfoTreeView.nowBodyModelItem.bodyModel.anatomy = localAnatomyName; }); //向菜单中添加菜单项
            //    }
            //    menu.ShowAsContext(); //显示菜单
            //}


            //if (GUILayout.Button(bodyModelInfoTreeView.nowBodyModelItem.bodyModel.system, GUILayout.Width(100))) //当点击按钮时，显示下拉菜单
            //{
            //    GenericMenu menu = new GenericMenu(); //初始化GenericMenu 
            //    for (int i = 0; i < ExcelDataConfig.systemNames.Length; i++)
            //    {
            //        var systemName = ExcelDataConfig.systemNames[i];
            //        menu.AddItem(new GUIContent(systemName), false, () => { bodyModelInfoTreeView.nowBodyModelItem.bodyModel.system = systemName; }); //向菜单中添加菜单项
            //    }
            //    menu.ShowAsContext(); //显示菜单
            //}

            //bodyModelInfoTreeView.nowBodyModelItem.modelObj = (GameObject)EditorGUILayout.ObjectField(bodyModelInfoTreeView.nowBodyModelItem.modelObj, typeof(GameObject), true, GUILayout.Width(100));
            //if (bodyModelInfoTreeView.nowBodyModelItem.modelObj != null) { bodyModelInfoTreeView.nowBodyModelItem.bodyModel.path = ExcelUtil.GetPath(bodyParent, bodyModelInfoTreeView.nowBodyModelItem.modelObj.transform); }
            #endregion
            EditorGUILayout.EndHorizontal();
        }
        /// <summary>
        /// 拖动excel 到窗口获取地址
        /// </summary>
        private void DragDropExcelPath()
        {
            //如果鼠标正在拖拽中或拖拽结束时，并且鼠标所在位置在文本输入框内  
            if ((Event.current.type == EventType.DragUpdated
              || Event.current.type == EventType.DragExited)
              && excelPathRect.Contains(Event.current.mousePosition))
            {
                //改变鼠标的外表  
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
                {
                    excelPath = DragAndDrop.paths[0];
                    excelPath = excelPath.Remove(0, 7);
                }
            }
        }
        /// <summary>
        /// 设置表头
        /// </summary>
        /// <returns></returns>
        static MultiColumnHeaderState CreateStateWith3Cols()
        {
            MultiColumnHeaderState.Column[] columns = null;
            columns = new[]
          {
             new MultiColumnHeaderState.Column
            {

                headerContent = new GUIContent("ID"),

                width = 40,
                minWidth = 20,
                maxWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                autoResize = false,
                allowToggleVisibility = true,
            },
            new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("模型名称"),
                width = 100,
                minWidth = 50,
                maxWidth = 100,
                headerTextAlignment = TextAlignment.Center,
                autoResize = false,
                allowToggleVisibility = true,
            },
            new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("中文名"),
                width = 50,
                minWidth = 30,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            },
            new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("英文名"),
                width = 100,
                minWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            },
            new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("描述"),
                width = 50,
                minWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            }, new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("部位"),
                width = 50,
                minWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            },
             new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("局部解剖"),
                width = 200,
                minWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            },
                new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("系统"),
                width = 100,
                minWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            },
             new MultiColumnHeaderState.Column
            {
                headerContent = new GUIContent("模型"),
                width = 100,
                minWidth = 50,
                headerTextAlignment = TextAlignment.Center,
                canSort = true,
                autoResize = false,
            },
        };

            var state = new MultiColumnHeaderState(columns);
            return state;
        }

    }
    class BodyModelInfoTreeView : TreeView
    {
        private Rect viewRect;
        public BodyModelItem nowBodyModelItem;
        private List<BodyModelItem> bodyModelTreeViews = new List<BodyModelItem>();
        public BodyModelItem root;

        public bool Ini = false;
        private Transform bodyRoot;
        public BodyModelInfoTreeView(Transform bodyRoot, TreeViewState treeViewState, MultiColumnHeader multiColumnHeader, Rect viewRect)
          : base(treeViewState, multiColumnHeader)
        {
            showAlternatingRowBackgrounds = true; //隔行显示颜色
            showBorder = true; //表格边框
            rowHeight = 25;
            this.viewRect = viewRect;
            this.bodyRoot = bodyRoot;
        }


        private bool isTissue = false;

        // private string[] fileNames;
        private string loadFileName;

        public void Load(string excelPath)
        {



            //加载excel表格
            ExcelDataWindowsEditor.IsMeridian = false;
            isTissue = false;
            string path = Application.dataPath + "/" + excelPath;
            loadFileName = path.Substring(path.LastIndexOf("/") + 1);
            loadFileName = loadFileName.Replace(".xlsx", "");

            if (loadFileName == "Tissue")
            {
                isTissue = true;
                loadFileName = "Tissue";
            }

            SaveManager.LoadExcelData(path, "Sheet", (excelWorksheet) =>
            {

                object[,] cells = excelWorksheet.Cells.Value as object[,];
                switch (loadFileName)
                {

                    case "Tissue": { LoadTissue(cells); } break;

                }
            });
            Reload();
            Ini = true;
        }

        private void LoadTissue(object[,] cells)
        {
            int itemIndex = 1;              //获取列数
            for (int rowIndex = 1; rowIndex < cells.GetLength(0); rowIndex++) //cells.GetLength(0)
            {
                if (cells[rowIndex, 0].ToString() != "")
                {
                    BodyModel bodyModelInfo = new BodyModel
                    {
                        modelName = cells[rowIndex, 0] == null ? "" : cells[rowIndex, 0].ToString(),
                        chineseName = cells[rowIndex, 1] == null ? "" : cells[rowIndex, 1].ToString(),
                        englishName = cells[rowIndex, 2] == null ? "" : cells[rowIndex, 2].ToString(),
                        infoWord = cells[rowIndex, 3] == null ? "" : cells[rowIndex, 3].ToString(),
                        part = cells[rowIndex, 4] == null ? "" : cells[rowIndex, 4].ToString(),
                        anatomy = cells[rowIndex, 5] == null ? "" : cells[rowIndex, 5].ToString(),
                        system = cells[rowIndex, 6] == null ? "" : cells[rowIndex, 6].ToString(),
                        path = cells[rowIndex, 7] == null ? "" : cells[rowIndex, 7].ToString(),
                    };


                    string anatomy = bodyModelInfo.anatomy;
                    bodyModelTreeViews.Add(new BodyModelItem()
                    {
                        id = itemIndex,
                        depth = 0,
                        displayName = bodyModelInfo.modelName,
                        bodyModel = bodyModelInfo,
                        localAnatomyIndex = GetLocalAnatomyIndex(anatomy)

                    });
                    itemIndex++;
                }

            }
        }
        public void SaveExcel(string excelPath)
        {
            string path = Application.dataPath + "/" + excelPath;
            switch (loadFileName)
            {

                case "Tissue": { SaveManager.CreateTable(path, "Sheet", SaveTissueTable); } break;
            }

            AssetDatabase.Refresh();

        }
        private void SaveTissueTable(ExcelWorksheet worksheet)
        {

            //添加列名
            worksheet.Cells[1, 1].Value = "模型名称";
            worksheet.Cells[1, 2].Value = "中文名";
            worksheet.Cells[1, 3].Value = "英文名";
            worksheet.Cells[1, 4].Value = "描述";
            worksheet.Cells[1, 5].Value = "部位";
            worksheet.Cells[1, 6].Value = "局部解剖";
            worksheet.Cells[1, 7].Value = "系统";
            worksheet.Cells[1, 8].Value = "地址";
            int whichRow = 2;//第一行已经写好了，所以从第二行开始
                             // 读取数据的长度，这个根据自己项目改动
            for (int i = 0; i < bodyModelTreeViews.Count; i++)
            {
                if (bodyModelTreeViews[i].modelObj != null) { bodyModelTreeViews[i].bodyModel.path = ""; }
                worksheet.Cells[whichRow, 1].Value = bodyModelTreeViews[i].bodyModel.modelName;
                worksheet.Cells[whichRow, 2].Value = bodyModelTreeViews[i].bodyModel.chineseName;
                worksheet.Cells[whichRow, 3].Value = bodyModelTreeViews[i].bodyModel.englishName;
                worksheet.Cells[whichRow, 4].Value = bodyModelTreeViews[i].bodyModel.infoWord;
                worksheet.Cells[whichRow, 5].Value = bodyModelTreeViews[i].bodyModel.part;
                worksheet.Cells[whichRow, 6].Value = localAnatomy[bodyModelTreeViews[i].localAnatomyIndex];
                worksheet.Cells[whichRow, 7].Value = bodyModelTreeViews[i].bodyModel.system;
                worksheet.Cells[whichRow, 8].Value = bodyModelTreeViews[i].bodyModel.path;
                whichRow++;

            }

        }



        protected override TreeViewItem BuildRoot()
        {
            Debug.Log("BuildRoot");
            root = new BodyModelItem
            {
                id = -1,
                depth = -1,
                displayName = "Root",
                bodyModel = new BodyModel()
                {
                    modelName = "模型名称",
                    chineseName = "中文名",
                    englishName = "英文名",
                    infoWord = "描述",
                    part = "地址",
                    anatomy = "局部解剖"
                }
            };
            for (int i = 0; i < bodyModelTreeViews.Count; i++)
            {
                root.AddChild(bodyModelTreeViews[i]);
            }
            SetupDepthsFromParentsAndChildren(root);
            dropRect = new Rect(0, 0, 1000, rowHeight * bodyModelTreeViews.Count);
            return root;
        }

        protected override void RowGUI(RowGUIArgs args)
        {
            //args.GetNumVisibleColumns()  如果对TreeView使用MultiColumnHeader，请使用此方法获取数字 当前显示在MultiColumnHeader中的可见列。
            for (int i = 0; i < args.GetNumVisibleColumns(); ++i)
                CellGUI(args.GetCellRect(i), args.item as BodyModelItem, args.GetColumn(i), ref args);
        }
        protected void MultiColumnHeader() { }
        private static string[] localAnatomy = new string[] { "头部", "左臂", "右臂", "躯干", "左腿", "右腿" };

        private void CellGUI(Rect cellRect, BodyModelItem item, int column, ref RowGUIArgs args)
        {
            MouseDropAddBodyModelItem();
            GUI.color = Color.white;//这里填充字体颜色
                                    // EditorGUIUtility.singleLineHeight
            CenterRectUsingSingleLineHeight(ref cellRect);
            switch (column)
            {
                case 0:
                    {
                        DefaultGUI.Label(cellRect, item.id.ToString(), args.selected, args.focused);
                    }
                    break;
                case 1:
                    {
                        DefaultGUI.Label(cellRect, item.bodyModel.modelName, args.selected, args.focused);
                    }
                    break;
                case 2:
                    item.bodyModel.chineseName = GUI.TextField(cellRect, item.bodyModel.chineseName);
                    break;
                case 3:
                    item.bodyModel.englishName = GUI.TextField(cellRect, item.bodyModel.englishName);
                    break;
                case 4:
                    DefaultGUI.Label(cellRect, item.bodyModel.infoWord, args.selected, args.focused);
                    break;
                case 5:

                    if (GUI.Button(cellRect, item.bodyModel.part))
                    {
                        GenericMenu menu = new GenericMenu(); //初始化GenericMenu 
                        for (int i = 0; i < ExcelDataWindowsEditor.partsDic[item.bodyModel.system].Length; i++)
                        {

                            var partName = ExcelDataWindowsEditor.partsDic[item.bodyModel.system][i];
                            menu.AddItem(new GUIContent(partName), false, () =>
                            {
                                item.bodyModel.part = partName;
                                if (GetSelection().Contains(item.id))
                                {
                                    SetAllSelectDataPart(partName);
                                }
                            }); //向菜单中添加菜单项
                        }
                        menu.ShowAsContext(); //显示菜单
                    }
                    break;
                case 7:
                    {

                        if (GUI.Button(cellRect, item.bodyModel.system)) //当点击按钮时，显示下拉菜单
                        {
                            GenericMenu menu = new GenericMenu(); //初始化GenericMenu  下拉菜单选项
                                                                  //for (int i = 0; i < ExcelDataConfig.systemNames.Length; i++)
                                                                  //{
                                                                  //    var systemName = ExcelDataConfig.systemNames[i];
                                                                  //    menu.AddItem(new GUIContent(systemName), false, () =>
                                                                  //    {
                                                                  //        item.bodyModel.system = systemName;
                                                                  //        if (GetSelection().Contains(item.id))
                                                                  //        {
                                                                  //            SetAllSelectDataSystemName(systemName);
                                                                  //        }
                                                                  //    }); //向菜单中添加菜单项
                                                                  //}
                            menu.ShowAsContext(); //显示菜单
                        }

                    }
                    break;
                case 6:
                    {

                        item.localAnatomyIndex = GUI.Toolbar(cellRect, item.localAnatomyIndex, localAnatomy);
                        if (GetSelection().Contains(item.id))
                        {
                            SetAllSelectDataLocalAnatomy(item.localAnatomyIndex);
                        }
                    }
                    break;
                case 8:
                    {

                        item.modelObj = UnityEditor.EditorGUI.ObjectField(cellRect, "", item.modelObj, typeof(GameObject), true) as GameObject;
                        // DefaultGUI.Label(cellRect, item.bodyModel.path, args.selected, args.focused);
                    }
                    break;
                case 9:
                    {
                        if (ExcelDataWindowsEditor.IsMeridian)
                        {
                            item.isDanger = GUI.Toggle(cellRect, item.isDanger, "");
                        }
                    }
                    break;
                case 10:
                    {
                        if (ExcelDataWindowsEditor.IsMeridian)
                        {
                            item.isProhibit = GUI.Toggle(cellRect, item.isProhibit, "");
                        }
                    }
                    break;
            }


        }

        private void SetAllSelectDataSystemName(string systemName)
        {
            for (int i = 0; i < GetSelection().Count; i++)
            {
                int index = GetSelection()[i];
                (FindItem(index, rootItem) as BodyModelItem).bodyModel.system = systemName;
            }
        }
        private void SetAllSelectDataLocalAnatomy(int localAnatomyIndex)
        {
            for (int i = 0; i < GetSelection().Count; i++)
            {
                int index = GetSelection()[i];
                (FindItem(index, rootItem) as BodyModelItem).localAnatomyIndex = localAnatomyIndex;
            }
            // UnityEngine.GUIUtility:ProcessEvent
        }
        private void SetAllSelectDataPart(string partName)
        {
            for (int i = 0; i < GetSelection().Count; i++)
            {
                int index = GetSelection()[i];
                (FindItem(index, rootItem) as BodyModelItem).bodyModel.part = partName;
            }
        }

        /// <summary>
        /// 移除一个item
        /// </summary>
        /// <param name="id"></param>
        protected override void ContextClickedItem(int id)
        {
            //if (AssetBundleModel.Model.DataSource.IsReadOnly())
            //{
            //    return;
            //}

            List<BodyModelItem> selectedNodes = new List<BodyModelItem>();
            foreach (var nodeID in GetSelection())
            {
                selectedNodes.Add(FindItem(nodeID, rootItem) as BodyModelItem);
                Debug.Log((FindItem(nodeID, rootItem) as BodyModelItem).bodyModel.modelName);
            }

            if (selectedNodes.Count > 0)
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("从Excel中移除选中的数据"), false, RemoveAssets, selectedNodes);
                menu.ShowAsContext();
            }

        }
        void RemoveAssets(object obj)
        {
            var selectedNodes = obj as List<BodyModelItem>;
            for (int i = 0; i < selectedNodes.Count; i++)
            {
                bodyModelTreeViews.Remove(selectedNodes[i]);
            }

            Reload();
        }
        /// <summary>
        /// 选中一个Item
        /// </summary>
        /// <param name="id"></param>
        protected override void SingleClickedItem(int id)
        {
            // Debug.Log(treeViewRect);
            if (GetSelection().Count != 0)
            {
                nowBodyModelItem = FindItem(GetSelection()[0], rootItem) as BodyModelItem;
                GameObject modelObject = nowBodyModelItem.modelObj;
                UnityEditor.EditorGUIUtility.PingObject(modelObject);
            }
        }
        //public bool isDragExited;
        //public bool isInViewRect;
        Rect dropRect = default;
        private void MouseDropAddBodyModelItem()
        {

            //isDragExited = (Event.current.type == EventType.MouseUp || Event.current.type == EventType.DragExited);
            ////isInViewRect = viewRect.Contains(Event.current.mousePosition);
            //if (Event.current.type == EventType.MouseDown)
            //{
            //    Debug.Log($"{viewRect.ToString()}---  {Event.current.mousePosition}---  {viewRect.Contains(Event.current.mousePosition)}");
            //}
            if ((Event.current.type == EventType.MouseUp || Event.current.type == EventType.DragExited) && dropRect.Contains(Event.current.mousePosition))
            {
                //Debug.Log(Event.current.type + "    " + Event.current.mousePosition);
                //改变鼠标的外表  
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                Object[] dropObjects = DragAndDrop.objectReferences;


                if (dropObjects.Length > 0)
                {
                    for (int i = 0; i < dropObjects.Length; i++)
                    {
                        GameObject modelObj = dropObjects[i] as GameObject;
                        if (bodyModelTreeViews.Where(O => O.modelObj == modelObj).Count() == 0)
                        {
                            var item = new BodyModelItem()
                            {
                                id = bodyModelTreeViews.Count + 1,
                                depth = 0,
                                displayName = modelObj.name,
                                bodyModel = new BodyModel
                                {
                                    modelName = modelObj.name,
                                    path = ""
                                },
                                modelObj = modelObj
                            };


                            bodyModelTreeViews.Add(item);
                            Debug.Log("添加一个模型" + modelObj.name);

                        }
                    }
                    Reload();


                }
            }
        }

        protected override DragAndDropVisualMode HandleDragAndDrop(DragAndDropArgs args)
        {
            return DragAndDropVisualMode.Generic;
        }
        private int GetLocalAnatomyIndex(string anatomy)
        {
            int index = 0;
            for (int i = 0; i < localAnatomy.Length; i++)
            {
                index = i;
                if (anatomy == localAnatomy[i])
                {
                    return index;
                }
            }
            return index;
        }

        public void Release()
        {

            bodyModelTreeViews.Clear();
            Ini = false;
        }
    }
    [SerializeField]
    public class BodyModel
    {
        public string name;
        public string modelName;
        public string path;
        public string chineseName;
        public string englishName;
        public string part;
        public string system;
        public string infoWord;
        public string anatomy;
    }
    [SerializeField]
    public class BodyModelItem : TreeViewItem
    {
        public BodyModel bodyModel;
        public GameObject modelObj;
        public int localAnatomyIndex;
        public int SystemNameIndex;
        public bool isDanger;
        /// <summary>
        /// 禁止针刺的穴位
        /// </summary>
        public bool isProhibit;
        internal BodyModelItem() : base(-1, -1) { }
        internal BodyModelItem(BodyModel a) : base()
        {
            bodyModel = a;

        }

    }


}


#endif
